<?php

namespace app\admin\controller\shopro\commission;

use addons\shopro\service\commission\Agent as AgentService;
use app\admin\controller\shopro\Common;
use app\admin\model\Admin;
use app\admin\model\shopro\commission\Log as LogModel;
use app\admin\model\User;
use think\Db;

//月度达标
class MonthlyCompliance extends Common
{
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\commission\MonthlyCompliance();
    }

    /**
     * 查看
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $exportConfig = (new \addons\shopro\library\Export())->getConfig();
            $this->assignconfig("save_type", $exportConfig['save_type'] ?? 'download');
            return $this->view->fetch();
        }
        $where=[];
        if($this->request->param("search")){
            $search=json_decode($this->request->param("search"),true);
            if(isset($search["year"])) $where["year"]=$search["year"][0];
            if(isset($search["month"])) $where["month"]=sprintf("%02s", $search["month"][0]);
        }
        $list = $this->model->with([ 'user','admin','account'])
            ->where($where)
            ->order("createtime desc,id desc")
            ->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $list);
    }
    /**
     * 详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }
        
        $detail = $this->model->with([ 'user','admin'])->where('id', $id)->find();
        if (!$detail) {
            $this->error(__('No Results were found'));
        }
        $this->success('详情', null, $detail);
    }
    // 发放月度奖金
    public function grant_set()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $this->success('发放月度奖金', null, []);
    }
    /**
     * 编辑
     *
     * @param  $id
     */
    public function edit($id = null)
    {
        $params = $this->request->only(['voucher', 'remark', 'is_grant']);

        $result = Db::transaction(function () use ($id, $params) {
            $row = $this->model->where('id', $id)->find();
            if (!$row) {
                $this->error('未找到该记录');
            }
            if ($row["is_grant"]==1) {
                $this->error('该月度奖金已发放');
            }
            $params["is_grant"]=1;
            $params["grant_time"]=time();
            $params["admin_id"]=$this->auth->id;
            $row->save($params);
            return true;
        });
        if ($result) {
            $this->success('发放成功', null, $result);
        } else {
            $this->error('发放失败');
        }
    }
    /**
     * 导出
     * */
    public function export()
    {
        $cellTitles = [
            // 订单表字段
            'id' => 'ID',
            'userId' => '会员编号',
            'account' => '收款账号',
            'bank' => '收款银行',
            'accountName' => '收款户名',
            'idCard' => '身份证号',
            'mobile' => '联系电话',
            'money' => '应发奖励',
            'rate' => '奖金比例',
            'performance' => '业绩金额',
            'performance_min' => '小市场业绩',
            'monthDate' => '时间：年 月',
            'createtime' => '创建时间',
            'remark' => '备注',
            'admin.nickname' => '操作人昵称',
        ];

        // 数据总条数
        $total = $this->model->sheepFilter()->count();
        if ($total <= 0) {
            $this->error('导出数据为空');
        }

        $export = new \addons\shopro\library\Export();
        $params = [
            'file_name' => '月度达标奖明细',
            'cell_titles' => $cellTitles,
            'total' => $total,
            'is_sub_cell' => true,
            'sub_start_cell' => 'activity_type_text',
            'sub_field' => 'items'
        ];

        $result = $export->export($params, function ($pages) use (&$total_order_amount, &$total_pay_fee, &$total_real_pay_fee, &$total_discount_fee, &$total_score_amount, $total) {
            $datas =  $this->model->sheepFilter()->with([ 'user','admin','account'])
                ->limit((($pages['page'] - 1) * $pages['list_rows']), $pages['list_rows'])
                ->select();
            $datas = collection($datas);
            $newDatas = [];
            $goods_list="";
            $items = [];
            foreach ($datas as &$item) {
                $data = [
                    'id' => $item['id'],
                    'userId' => $item["user"]["id"]??0,
                    'bank' => isset($item["account"]["account_header"])?" ".$item["account"]["account_header"]:"",
                    'account' => isset($item["account"]["account_no"])?" ".$item["account"]["account_no"]:"",
                    'accountName' => isset($item["account"]["account_name"])?$item["account"]["account_name"]:"",
                    'idCard' => isset($item["user"]["ID_number"])?" ".$item["user"]["ID_number"]:"",
                    'mobile' => isset($item["user"]["mobile"])?" ".$item["user"]["mobile"]:"",
                    'money' => $item["money"],
                    'rate' => $item["rate"],
                    'performance' => $item["performance"],
                    'performance_min' => $item["performance_min"],
                    'monthDate' => $item["year"].$item["month"],
                    'createtime' => $item["createtime"],
                    'remark' => $item["remark"],
                    'admin.nickname' => $item["admin"]["nickname"]??'',
                ];

                $data['items'] = $items;
                $data['goods_list'] = $goods_list;
                $newDatas[] = $data;
            }
            return $newDatas;
        });

        $this->success('导出成功' . (isset($result['file_path']) && $result['file_path'] ? '，请在服务器: “' . $result['file_path'] . '” 查看' : ''), null, $result);
    }
}
